package top.lingchen.webfluxdemo2.handler;

import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import top.lingchen.webfluxdemo2.entity.User;
import top.lingchen.webfluxdemo2.service.UserService;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @Author 凌宸
 * @create 2021-12-01 下午 7:11
 * @Description
 * @Version 1.0
 */
public class UserHandler {
    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    // 根据 id 查询
    public Mono<ServerResponse> getUserById(ServerRequest request){
        // 获取 id 值
        String id = request.pathVariable("id");
        int userId = Integer.parseInt(id);
        //空值处理
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();
        // 调用 service 方法得到数据
        Mono<User> userMono = this.userService.getUserById(userId);
        // 把 userMono 进行转换并返回
        // 使用 Reactor flatMap 操作符
        return userMono.flatMap(person -> ServerResponse.ok().
                contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(person)))
                .switchIfEmpty(notFound);
    }
    // 查询所有
    public Mono<ServerResponse> getAllUsers(ServerRequest request){
        Flux<User> userFlux = this.userService.getAllUsers();
        return ServerResponse.ok().contentType(APPLICATION_JSON)
                .body(userFlux, User.class);
    }
    // 添加
    public Mono<ServerResponse> saveUser(ServerRequest request){
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
    }
}
